#!/usr/bin/env python
# coding=utf-8
# 基于应用名获取主机地址
# python cluster.py pro-blog

from unittest import result
import requests
import json
import sys

def get_server_ip(url,headers,lst):
    for i in lst:
        server_id_url = '{0}{1}'.format(url,i)
        ret =  requests.get(url=server_id_url,headers=headers ) 
        result = '[{0}]-{1}'.format(ret.json()['data']['hostname'],ret.json()['data']['ip'])
        print(result)

def getToken(url,data):
    ret = requests.post(url=url, json=data) 
    if ret.status_code == 200 and 'token' in ret.json()['data']:
        token = ret.json()['data']['token']
    else:
        token = Null
    return token

def search_API(*args, **kwargs):
    headers = {
            'Authorization': 'Bearer {}'.format(getToken(args[0],data=kwargs['data'])),
    }
    cluster_url = '{0}{1}'.format(args[1],kwargs['name'])
    ret =  requests.get(url=cluster_url,headers=headers ) 
    hosts = ret.json()['data']['results'][0]['host_id']

    if hosts:
        servers_url = '{0}'.format(args[2])
        get_server_ip(servers_url,headers,hosts)


if __name__ == '__main__':
    URL = 'http://127.0.0.1:8000'
    Login_API = '{}/api/oauth/login/'.format(URL)
    cluster_API = '{}/api/app/applications/?&search='.format(URL)
    servers_API = '{}/api/asset/servers/'.format(URL)
    
    data = {
    "username":"admin",
    "password": "123456"
    }

    name = sys.argv[1]  # 'pro-blog'
    search_API(Login_API,cluster_API,servers_API,data=data,name=name)